package com.springboot.springboot2.converter;

import com.springboot.springboot2.bean.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @ClassName:
 * @author: CKC
 * @DateTime: 2021/1/28 15:57
 *
 * 自定义的  xxxConverter 协议
 */
public class XxxMessageConverter implements HttpMessageConverter<Person> {
    
    /**
     * 是否支持读功能 是返回true
     * 读功能:
     *  客户端传来的数据能都使用  @RequestBody标注
     *
     */
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }
    
    /**
     * 能不能写(是否返回客户端数据)
     */
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        //要返回true
        /** 类型是 Person才能写 */
        return clazz.isAssignableFrom(Person.class);
    }
    
    
    /**getSupportedMediaTypes 获取所支持的媒体类型（重要）
     *
     * 服务器要统计所有的MessageConverter都能写出那些内容数据类型
     * application/xxx
     * @return
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/xxx");
    }
    
    @Override
    public Person read(Class<? extends Person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }
    
    @Override
    public void write(Person person, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //自定义协议数据写出
        String date= person.getUserName()+";"+person.getAge()+";"+person.getBirth();
    
        //写出去
        OutputStream body = outputMessage.getBody();
    
        body.write(date.getBytes());
    }
}
